package com.paipaideli.ui.home;

import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jakewharton.rxbinding2.view.RxView;
import com.paipaideli.R;
import com.paipaideli.common.base.BasePresenterFragment;
import com.paipaideli.common.http.Api;
import com.paipaideli.common.pullrefresh.TStatusView;
import com.paipaideli.common.utils.ToastUtil;
import com.paipaideli.ui.home.bean.TreeBean;
import com.paipaideli.ui.home.water.WaterView;
import com.paipaideli.ui.profit.MentorActivity;
import com.paipaideli.ui.profit.PriceShowInterface;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class ProfitFragment extends BasePresenterFragment implements PriceShowInterface {

    Unbinder unbinder;
    @BindView(R.id.top_back)
    RelativeLayout top_back;
    @BindView(R.id.top_title)
    TextView top_title;
    @BindView(R.id.view_water)
    WaterView mWaterView;
    @BindView(R.id.image_profit_st)
    ImageView image_profit_st;
    @BindView(R.id.tree)
    ImageView tree;
    @BindView(R.id.image_profit_all)
    ImageView image_profit_all;
    @BindView(R.id.btn_price)
    Button btn_price;

    @BindView(R.id.bg_statusview)
    TStatusView bg_statusview;


    private List<TreeBean.Data.RewardRes> list = new ArrayList<>();

    public static ProfitFragment newInstance() {
        ProfitFragment fragment = new ProfitFragment();
        return fragment;
    }

    //收钱的声音
    AssetManager assetManager;
    MediaPlayer player = null;
    AssetFileDescriptor fileDescriptor = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profit, container, false);
        unbinder = ButterKnife.bind(this, view);


        player = new MediaPlayer();
        assetManager = getResources().getAssets();
        try {
            player.reset();
            fileDescriptor = assetManager.openFd("simpleCoin.wav");
            player.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor.getStartOffset());
            player.prepare();

        } catch (Exception e) {
            e.getMessage();
        }
        return view;
    }

    @Override
    public void initView() {
        top_back.setVisibility(View.GONE);
        top_title.setText("收益");

        WaterView.setListener(this);//注册接口方法

        getWidth();//获取屏幕宽度

        //师徒关系
        RxView.clicks(image_profit_st).subscribe(o -> {
            Intent intent = new Intent(getActivity(), MentorActivity.class);
            startActivity(intent);
        }, throwable -> {
        });

        //一键按钮点击
        RxView.clicks(image_profit_all).subscribe(o -> {
            if (list.size() > 0) {
                extractAll();
            } else {
                ToastUtil.show("当前无可收收益！");
            }
        }, throwable -> {
        });

        initDate();
    }

    public void initDate() {
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("curPage", "1");
            requestData.put("pageSize", "10");
        } catch (Exception e) {
            e.getMessage();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().tree(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    if (request.code.equals("200")) {
                        btn_price.setText(request.data.bounty + "");
                        list = request.data.rewardRes;
                        mWaterView.removeAllViews();
                        mWaterView.setWaters(list);
                        bg_statusview.finish();
                    } else {
                        bg_statusview.finish();
                        ToastUtil.show(request.msg);
                    }
                }, throwable -> {
                    bg_statusview.finish();
                    Log.e(TAG, "error", throwable);
                });
    }

    private void getWidth() {
        //2、通过Resources获取屏幕的宽高
        DisplayMetrics dm = getResources().getDisplayMetrics();
        int width = dm.widthPixels;
        LayoutParams para;
        para = tree.getLayoutParams();
        para.height = width * 81 / 75;
        para.width = width;
        tree.setLayoutParams(para);
    }

    @Override
    public void Receive(String message, String id, int i, View view) {
        extract(message, id, i, view);
    }

    private void extract(String message, String id, int i, View view) {
        mWaterView.removeView(view);
        // ToastUtil.show(mWaterView.getChildCount()+"");


        if (player != null) {
            if (player.isPlaying()) {
                try {
                    player.reset();
                    player.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor.getStartOffset());
                    player.prepare();
                    player.start();
                } catch (Exception e) {
                    e.getMessage();
                }
            } else {
                player.start();
            }
        }
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("id", id);
        } catch (Exception e) {
            e.getMessage();
        }
        /*if (i == 10) {
            image_profit_all.setVisibility(View.VISIBLE);
            initDate();
        }*/
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().extract(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    if (request.getCode().equals("200")) {
                        double price = Double.valueOf(message) + Double.valueOf(btn_price.getText().toString());
                        java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");

                        btn_price.setText(df.format(price) + "");
                        if (mWaterView.getChildCount() == 0) {
                            image_profit_all.setVisibility(View.VISIBLE);
                            initDate();
                        }
                    } else {
                        ToastUtil.show(request.getMessage());
                    }
                }, throwable -> {
                    Log.e(TAG, "error", throwable);
                });
    }

    private void extractAll() {
        if (list != null) {
            list.clear();
            mWaterView.removeAllViews();
        }
        //收钱的声音
        AssetManager assetManager;
        MediaPlayer player = null;
        player = new MediaPlayer();
        assetManager = getResources().getAssets();
        try {
            AssetFileDescriptor fileDescriptor = assetManager.openFd("allCoin.wav");
            player.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor.getStartOffset());
            player.prepare();
            player.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

        JSONObject requestData = new JSONObject();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().extractAll(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    if (request.getCode().equals("200")) {
                        initDate();
                    } else {
                        ToastUtil.show(request.getMessage());
                    }
                }, throwable -> {
                    Log.e(TAG, "error", throwable);
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initDate();
        }
    }
}
